import React, { useState, useEffect, useMemo, useContext, useReducer, useRef } from "react";
import { Layout, notification, message } from "antd";
import MyHeader from "./MyHeader";
import MySlider from "./MySlider";
import MyContent from "./MyContent";
import { connect } from "react-redux";
import io from "socket.io-client";
import BraftEditor from "braft-editor";
import axios from 'axios' ;
import "braft-editor/dist/index.css";
import Context from "./Context";
import replaceImg from "../../utils/replacestr";
import HomeLoading from "../../components/Loading/HomeLoading";
import resolve from "resolve";
const { Header, Sider, Content } = Layout;

const data = {
  chatList: [],
  chatroomid: 0,
  latestobj: [],
};

const getCon = (html) => {
  return { __html: html };
};
const preId = null ;
const images = [
  `${process.env.REACT_APP_BASE_URL}/images/robet.jpg`,
  `${process.env.REACT_APP_BASE_URL}/images/883.jpg`,
  `${process.env.REACT_APP_BASE_URL}/images/820.jpg`,
  `${process.env.REACT_APP_BASE_URL}/images/835.jpg`,
];
console.log(process.env.REACT_APP_BASE_URL);
function chatInfor(prevState, action) {
  let state = JSON.parse(JSON.stringify(prevState));
  switch (action.type) {
    case "addList":
      state.chatList = [...state.chatList, action.data];
      return state;
    case "init":
      state.chatList = action.data;
      return state;
    case "chooseId":
      state.chatroomid = action.id;
      return state;
    case "initlist":
      state.latestobj = [action.lastest1, action.lastest2, action.lastest3];
      console.log(action.lastest1);
      return state;
    case "updatelist":
      state.latestobj[parseInt(action.num - 1)] = action.data;
      return state;
    default:
      return state;
  }
}
// let ios = null;
function App({ UpateUserInfo, history, changeContent, initWebsocket }) {
  const [connecttimes, setconnecttimes] = useState(0);
  const chatdom = useRef();
  const chatRef = useRef();
  const connectt = useRef();
  const recon = useRef();
  const [useInfo,setuseInfo] = useState(null) ;
  const [loading, setLoading] = useState(true);
  const [state, dispatch] = useReducer(chatInfor, data);
  const [collapsed, setCollpased] = useState(false);
  const [flag, setFlag] = useState(false);
  const [reconnecttime, setreconnection] = useState(0);
  const Up  = useMemo(()=> {
    return UpateUserInfo.userInfo
  },[JSON.parse(JSON.stringify(UpateUserInfo.userInfo))])
  const loadBigImgAsync = (url) => {
    // 为了提前加载图片
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const image = new Image();
        image.onload = function () {
          resolve(url);
        };
        image.onerror = function () {
          console.log("图片加载错误");
        };
        image.src = url;
      }, 100);
    });
  };
  // const loadingImagses = async function (url) {
  //   await loadBigImgAsync(url);
  // };
  const toggle = () => {
    console.log(1);
    setCollpased(!collapsed);
  };
  const color = useMemo(() => {
    let col = "lightblue";
    let primaryColor = localStorage.getItem("primaryColor");
    if (primaryColor !== null) {
      col = primaryColor;
    }
    return col;
  });
  // const loadImages =async function() {
  //   let res = await loadingimages(images) ;
  //   setLoading(prev => false) ;
  // }
  // const userInfo = useMemo(()=>{
  //   let res = {...UpateUserInfo.userInfo}
  //   return res ;
  // },[{...UpateUserInfo.userInfo}]);
  const notifyMessage = (data) => {
    if (
      data.type == "success" &&
      connectt.current.innerText === "0" &&
      data.userid === UpateUserInfo.userInfo.id
    ) {
      notification[data.type]({
        message: "连接成功",
        description: "你已经成功登录",
      });
    } else if (data.type == "info") {
      notification[data.type]({
        message: "退出聊天",
        description: data.message,
      });
    } else if (data.type == "error") {
      notification[data.type]({
        message: "连接异常",
        description: data.message,
      });
    }
    if (data.type == "success" && data.userid !== UpateUserInfo.userInfo.id) {
      notification[data.type]({
        message: "连接成功",
        description: data.message,
      });
    }
  };
  const getchat = (data) => {
    if (data.ok && chatdom.current) {
      // if (
      //   parseInt(data.userid) != parseInt(UpateUserInfo.userInfo.id) &&
      //   parseInt(chatdom.current.innerText) == 3
      // ) {
      //   return;
      // } else {
      console.log(data.robetuserid);
      // if(parseInt(data.robetuserid) == parseInt(UpateUserInfo.userInfo.id) || ) {
      if (
        parseInt(data.robetuserid) != parseInt(UpateUserInfo.userInfo.id) &&
        data.robetuserid !== null
      ) {
        return;
      } else {
        dispatch({
          type: "updatelist",
          num: data.chatroomid,
          data,
        });
      }

      // }

      // }
      console.log(BraftEditor.createEditorState(new Buffer(data.content).toString()).toHTML());
      notification["success"]({
        message:
          parseInt(data.userid) != parseInt(UpateUserInfo.userInfo.id)
            ? data.username +
              " 在 " +
              ["聊天1群", "聊天2群", "智能对话"][parseInt(data.chatroomid) - 1] +
              " 发送了:"
            : "您" +
              " 在 " +
              ["聊天1群", "聊天2群", "智能对话"][parseInt(data.chatroomid) - 1] +
              " 发送了:",
        description: (
          <div
            dangerouslySetInnerHTML={{
              __html: replaceImg(
                BraftEditor.createEditorState(new Buffer(data.content).toString()).toHTML()
              ),
            }}
          ></div>
        ),
      });
      if (parseInt(data.chatroomid) == parseInt(chatdom.current.innerText)) {
        // setchatList((prev) => [...chatList, data]);
        dispatch({
          type: "addList",
          data,
        });

        if (document.querySelector(".sayList")) {
          chatRef.current.scrollToBottom();
        }
        // setBarHeights((prev) => document.querySelector(".sayList").scrollHeight);
        // document.querySelector('.chatscrollbar').
        // setTimeout(()=>{
        // document.querySelector(".sayList").scrollTop = document.querySelector(
        //   ".sayList"
        // ).scrollHeight;
      }
    } else {
      return message.error(data);
    }
  };

  const chatroomid = useMemo(() => {
    // console.log(chatroomid)
    return state.chatroomid;
  }, [state.chatroomid]);
  // 必须等待redux的信息到达 
  // const waitInfo = function () {
  //   return new Promise(async (reslove,reject)=> {
  //     // let { data: res } = await axios.get("/ap/user");
  //     // if (res.ok !== 0) { 
  //     // //   // 防止数据没有传输及时
  //     //   changeContent({ type: "getuser", data: res.data });
  //     //   changeContent({ type: "issystemon", flat: "1" });
  //       // setuseInfo(prev => res.data) ;
  //       reslove();
  //     //   // getUserInfo({type:'getHistory',history:history})
  //     // }
     
      
  //   })
  // }
  useEffect(() => {
    // loadingimages(images)
    // const token = localStorage.getItem('mysystemtoken');
    if ( UpateUserInfo.userInfo == null||!UpateUserInfo.userInfo.id) {
      console.log('有无执行代码');
      history.push("/login");
      return;
    }

    // waitInfo().then(res => {
    // 加载首张就行
    loadBigImgAsync(images[0]).then(() => {
      setLoading((prev) => false);
      let theme = JSON.parse(JSON.stringify(localStorage.getItem("theme")));
      // console.log(typeof theme);
      changeContent({ type: "else" });
      changeContent({ type: "changetheme", value: theme ? theme : "dark" });
      loadBigImgAsync(images[1]).then(()=>{})
      loadBigImgAsync(images[2]).then(()=>{})
      loadBigImgAsync(images[3]).then(()=>{})
      if (!theme) {
        localStorage.setItem("theme", "dark");
      }
      window.less
        .modifyVars({
          "@primary-color": color,
        })
        .then(() => {})
        .catch((error) => {
          // message.error(`Failed to update theme`);
        });
      const websocket = io("http://www.chenzefan.xyz:7001/", {
        query: {
          token: localStorage.getItem("mysystemtoken"),
          userid: UpateUserInfo.userInfo.id,
        },
      });
      changeContent({ type: "connected", isconnected: true });

      // 初始化连接用户socket
      // initWebsocket({token: localStorage.getItem("token"), userid:UpateUserInfo.userInfo.id,...UpateUserInfo.userInfo}) ;
      // ios = io(axios.defaults.baseURL, {
      //   query: {
      //     token: localStorage.getItem("token"),
      //     userid:UpateUserInfo.userInfo.id
      //   },
      //   // reconnection:true
      // });
      websocket.on("notify", notifyMessage);
      websocket.on("chat", getchat);
      websocket.on("connect_error", () => {
        setreconnection((prev) => 0);
        if (connectt.current.innerText === "0") {
          setconnecttimes((prev) => 1);
        }
        changeContent({ type: "connected", isconnected: false });
        console.log(UpateUserInfo.sysconnecting);
        if (UpateUserInfo.sysconnecting == "1" && connectt.current.innerText === "1") {
          console.log(connectt.current.innerText);
          notification.error({
            message: "连接异常",
            description: "与服务器断开了连接",
          });
          let loading = null;
          if (connectt.current.innerText === "1") {
            loading = message.loading("网络重连中,请等待...", 0);
          }
          if (initWebsocket.websocket !== null) {
            websocket.on("reconnect", () => {
              setreconnection((prev) => ++prev);
              changeContent({ type: "connected", isconnected: true });
              setFlag((prev) => true);
              setTimeout(loading);
              setconnecttimes((prev) => 1);
              if (recon.current.innerText === "1") {
                notification["success"]({
                  message: "提示",
                  description: "网络重新连接成功",
                });
              }
            });
            if (connectt.current.innerText === "1") {
              setTimeout(() => {
                if (!flag) {
                  message.error("长时间无响应,建议刷新连接,重启系统");
                }
              }, 5000);
            }
            // websocket.on('reconnecting',()=> {
            //   message.loading('重连中,请等待...');
            // });
            websocket.on("reconnect_error", () => {
              if (connectt.current.innerText === "1") {
                notification.error({
                  message: "重新连接失败",
                  description: "通讯重连失败",
                });
              }
              setconnecttimes((prev) => ++prev);
            });
          }
        }
      });
      changeContent({
        type: "setwebsocket",
        websocket,
      });
    });

    // }).catch(err => {
    //   history.push("/login");
    // })

    // window.ios = ios;
    return () => {
      // ios.off('connect');
      // ios.close();
    };
  }, []);
  return (
    <>
      {loading ? (
        <HomeLoading />
      ) : (
        <Layout>
          <Context.Provider value={{ dispatch, state, chatRef }}>
            <Sider trigger={null} collapsible collapsed={collapsed} theme={UpateUserInfo.theme}>
              <MySlider collapsed={collapsed} />
            </Sider>
            <Layout className="site-layout">
              <Header
                className="site-layout-background"
                style={{
                  padding: 0,
                  backgroundColor: UpateUserInfo.theme == "dark" ? "#001529" : "white",
                  transition: "all 0.2s",
                }}
              >
                <MyHeader collapsed={collapsed} toggle={toggle} />
              </Header>
              <span className="chatroomid" style={{ display: "none" }} ref={chatdom}>
                {chatroomid}
              </span>
              <span className="cccc" style={{ display: "none" }} ref={connectt}>
                {connecttimes}
              </span>
              <span className="ccxx" style={{ display: "none" }} ref={recon}>
                {reconnecttime}
              </span>
              <Content className="site-layout-background">
                <MyContent />
              </Content>
            </Layout>
          </Context.Provider>
        </Layout>
      )}
    </>
  );
}
export default connect(
  (state) => state,
  (dispatch) => {
    return { changeContent: (data) => dispatch(data) };
  }

  // }
)(App);
